package com.example.heimashop.viewmodel;

import androidx.lifecycle.MutableLiveData;

import com.example.heimashop.api.RetrofitClient;
import com.example.heimashop.base.BaseViewModel;
import com.example.heimashop.model.Category;

import java.util.List;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.schedulers.Schedulers;

/**
 * 分类ViewModel
 */
public class CategoryViewModel extends BaseViewModel {

    public MutableLiveData<List<Category>> categoriesLiveData = new MutableLiveData<>();
    public MutableLiveData<String> errorLiveData = new MutableLiveData<>();

    /**
     * 获取分类数据
     */
    public void getCategories() {
        addDisposable(RetrofitClient.getInstance()
                .getApiService()
                .getCategories()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        response -> {
                            if (response.isSuccess()) {
                                categoriesLiveData.setValue(response.getMessage());
                            } else {
                                errorLiveData.setValue(response.getMeta() != null ? response.getMeta().getMsg() : "获取失败");
                            }
                        },
                        throwable -> errorLiveData.setValue(throwable.getMessage())
                ));
    }
}
